<?php

namespace App\Http\Controllers\Api\Merchant;

use App\Http\Services\MeiTuan\ApiList;
use App\Http\Services\MeiTuan\Config;
use App\Http\Services\MeiTuan\ServiceProviderApiList;
use App\Http\Services\ToolsManager;
use App\MeituanShop;
use App\OrderAddress;
use App\OrderDelivery;
use App\Orders;
use DB;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class MeituanController extends Controller
{
    //订单
    public function sendToMeituan(Request $request)
    {
//        $order_id = $request->input('order_id');
//        if (!$order_id)
//            return response()->json(['level'=>'error','message'=>'参数错误','data'=>'']);
//        $order = Orders::whereId($order_id)->first();
//        if (!$order)
//            return response()->json(['level'=>'error','message'=>'订单不存在','data'=>'']);
////        if (!in_array($order->status,[2,3,4,5,6,7,8,9,10,11,12,13,14])){
////            //TODO 限制发单
////            return response()->json(['level'=>'error','message'=>'限制发单','data'=>'']);
////        };
//        $delivery_id = ToolsManager::getDeliveryId($order->merchant_id,$order->id);
//        $orderDelivery = OrderDelivery::whereOrderId($order->id)
//            ->whereDeliveryId($delivery_id)
//            ->orderBy('id','desc')
//            ->first();
        //已发单
//        if ($orderDelivery){
//            $orderDelivery->status_name = OrderDelivery::getStatusName($orderDelivery->status);
//            return response()->json(['level'=>'success','message'=>'已发单','data'=>$orderDelivery]);
//        }
        $goods = [];
        $goods_info = [];
        $temp1 = (object)[
            'goodCount' => 1,
            'goodName'  => '测试货物1',
            'goodPrice' => 9.99,
            'goodUnit'  => '盒'
        ];
        $temp2 = (object)[
            'goodCount' => 1,
            'goodName'  => '测试货物2',
            'goodPrice' => 1.23,
            'goodUnit'  => '包'
        ];
        array_push($goods_info,$temp1,$temp2);
//        array_push($goods,$goods_info);
       $goods['goods']=$goods_info;
        //发单
        //生成记录
//        try {
//            $today_start = date('Y-m-d 00:00:00');
//            DB::beginTransaction();
////            $today_num = OrderDelivery::whereEnterpriseId($order->enterprise_id)
////                ->whereMerchantId($order->merchant_id)
////                ->where('created_at','>=',$today_start)
////                ->count();
////            $next_num = $today_num + 1;
////            $receive_addr           = OrderAddress::whereId($order->order_address_id)->first();
////            if (!$receive_addr)
////                return response()->json(['level'=>'error','message'=>'订单异常，无法处理','data'=>'']);
//            $shop_id = 'test_0001';
//            $record                 = new OrderDelivery();
//            $record->order_id       = $order->id;
//            $record->delivery_id    = $delivery_id;
//            $record->merchant_id    = $order->merchant_id;
//            $record->enterprise_id  = $order->enterprise_id;
//            $record->outer_order_source_desc    = '202';                //202商家小程序-微信
//            $record->outer_order_source_no      = $order->order_num;    //原平台订单号
//            $record->shop_id                    = $shop_id;    //取货门店
//            $record->delivery_service_code      = '4011';
//            $record->receiver_name              = $receive_addr->consignee;//收件人
//            $record->receiver_address           = $receive_addr->area.'-'.$receive_addr->address;//区-地址
//            $record->receiver_phone             = $receive_addr->phone;//区-地址
//            $record->receiver_lng               = intval(round($receive_addr->lng,6) * 100000);//区-地址
//            $record->receiver_lat               = intval(round($receive_addr->lat,6) * 100000);//区-地址
//            $record->goods_value                = $order->discount_price;   //货物价格
//            $record->goods_weight               = 1.00;                     //货物重量
//            $record->goods_detail               = json_encode((object)$goods,JSON_UNESCAPED_UNICODE);      //货物详情
//            $record->poi_seq                    = $next_num;                //流水号
//            $record->save();
//            DB::commit();
//        } catch (\Exception $e) {
//            \Log::error($e->getMessage());
//            \Log::error($e->getTraceAsString());
//            return response()->json(['level'=>'error','message'=>'发生错误：'.$e->getMessage(),'data'=>'']);
//        }


        //113.538402,23.20413
//        $payload = [
//            'delivery_id'   =>1001001,
//            'order_id'      =>'1',
//            'outer_order_source_desc'=>'202',
//            'outer_order_source_no' => '202001270001',
//            'shop_id'               =>'test_0001',
//            'delivery_service_code' =>'4011',
//            'receiver_name'         => '程序员',
//            'receiver_address'      => '广东省广州市黄埔区林逸街114号',
//            'receiver_phone'        => '13800138000',
//            'receiver_lng'          => 113538402,
//            'receiver_lat'          => 23204130,
//            'goods_value'           => 12.34,
//            'goods_weight'          => 1.00,
//            'goods_detail'          => json_encode($goods,JSON_UNESCAPED_UNICODE),
//            'goods_pickup_info'     => '',
//            'goods_delivery_info'   => '',
//            'poi_seq'               => '',
//        ];
        $payload = [
            'delivery_id'   => (int)1001001001,
            'order_id'      => 100,
            'outer_order_source_desc'=>'202',
            'outer_order_source_no' => 12345678,
            'shop_id'               =>'test_0001',
            'delivery_service_code' =>'4011',
            'receiver_name'         => '测试收件人',
            'receiver_address'      => '测试地址',
            'receiver_phone'        => '13800138000',
            'receiver_lng'          => 113538402,
            'receiver_lat'          => 23204130,
            'goods_value'           => 12.34,
            'goods_weight'          => 1.00,
            'goods_detail'          => json_encode($goods,JSON_UNESCAPED_UNICODE),
//            'goods_pickup_info'     => '',
//            'goods_delivery_info'   => '',
            'poi_seq'               => 1,
        ];
        $meituan = self::isvApiList();
        $response = $meituan->createByShop($payload);
//        return $response;
        return response()->json(['response'=>$response]);
    }
    public function cancelMeituanOrder(Request $request){
        $delivery_id        = $request->input('delivery_id');
        $mt_peisong_id      = $request->input('mt_peisong_id');
        $cancel_reason_id   = $request->input('cancel_reason_id');
        $cancel_reason      = $request->input('cancel_reason');
        $payload = [
            'delivery_id'   =>(int)$delivery_id,
            'mt_peisong_id' =>$mt_peisong_id,
            'cancel_reason_id'=>(int)$cancel_reason_id,
            'cancel_reason'=>$cancel_reason
        ];
        $meituan = self::isvApiList();
        $response = $meituan->cancelOrder($payload);
        return response()->json(['response'=>$response]);
    }
    public function checkMeituanOrder(Request $request){
        $delivery_id        = $request->input('delivery_id');
        $mt_peisong_id      = $request->input('mt_peisong_id');
        $payload = [
            'delivery_id'   =>(int)$delivery_id,
            'mt_peisong_id' =>$mt_peisong_id,
        ];
        $meituan = self::isvApiList();
        $response = $meituan->queryOrder($payload);
        return response()->json(['response'=>$response]);
    }

    //门店
    public function createDeliveryShop(Request $request){
        $check_parameter    = $this->checkCreateShopParameter($request);
        if ($check_parameter)
            return $check_parameter;
        $shop_id        = $request->input('shop_id');
        $shop_name      = $request->input('shop_name');
        $category       = $request->input('category');
        $second_category= $request->input('second_category');
        $contact_name   = $request->input('contact_name');
        $contact_phone  = $request->input('contact_phone');
        $contact_email  = $request->input('contact_email');
        $shop_address   = $request->input('shop_address');
        $shop_address_detail = $request->input('shop_address_detail');
        $shop_lng       = $request->input('shop_lng');
        $shop_lat       = $request->input('shop_lat');
        $coordinate_type    = $request->input('coordinate_type',0);
        $delivery_service_codes = $request->input('delivery_service_codes','4011');
        $business_hours     = $request->input('business_hours');
        $status             = $request->input('status',1);
        try {
            DB::beginTransaction();
            $mt_shop = MeituanShop::whereShopId($shop_id)->lockForUpdate()->first();
            if (!$mt_shop){
                $mt_shop = new MeituanShop();
                $mt_shop->shop_id       = $shop_id;
            }
            $mt_shop->shop_name         = $shop_name;
            $mt_shop->category          = $category;
            $mt_shop->second_category   = $second_category;
            $mt_shop->contact_name      = $contact_name;
            $mt_shop->contact_phone     = $contact_phone;
            $mt_shop->contact_email     = $contact_email;
            $mt_shop->shop_address      = $shop_address;
            $mt_shop->shop_address_detail = $shop_address_detail;
            $mt_shop->shop_lng          = $shop_lng;
            $mt_shop->shop_lat          = $shop_lat;
            $mt_shop->coordinate_type   = $coordinate_type;
            $mt_shop->delivery_service_codes = $delivery_service_codes;
            $mt_shop->business_hours    = $business_hours;
            if ($status == 2){
                //2：禁止店铺使用配送服务
                $mt_shop->status        = 2 ;
            }
            $mt_shop->save();

            $payload = [
                'shop_id'       => $shop_id,
                'shop_name'     => $shop_name,
                'category'      => (int)$mt_shop->category,
                'second_category'=> (int)$mt_shop->second_category,
                'contact_name'  =>$mt_shop->contact_name,
                'contact_phone' =>$mt_shop->contact_phone,
                'contact_email' =>$mt_shop->contact_email,
                'shop_address'  =>$mt_shop->shop_address,
                'shop_address_detail'=>$mt_shop->shop_address_detail,
                'shop_lng'      =>$mt_shop->shop_lng,
                'shop_lat'      =>$mt_shop->shop_lat,
                'coordinate_type'=>$mt_shop->coordinate_type,
                'delivery_service_codes'=>$mt_shop->delivery_service_codes,
                'business_hours'=>$mt_shop->business_hours,
            ];
            $meituan = self::isvApiList();
            $response = $meituan->createShop($payload);
            DB::commit();
            if (!$response){
                return response()->json(['level'=>'error','message'=>'未成功向美团发出请求，请联系开发人员查看日志','data'=>null]);
            }
            if (!$response->send_status)
                return response()->json(['level'=>'error','message'=>'网络请求失败，请联系开发人员查看日志','data'=>null]);
            if (!$response->operation_status)
                return response()->json(['level'=>'error','message'=>$response->msg,'data'=>$response->data]);
            return $this->successResponse($response->msg,$response->data);
        } catch (\Exception $exception){
            \Log::error($exception->getMessage());
            \Log::error($exception->getTraceAsString());
            DB::rollBack();
            return response()->json(['level'=>'error','message'=>'发生错误：'.$exception->getMessage()]);
        }
    }
    public function checkShopInfo(Request $request){
        $shop_id            = $request->input('shop_id');
        $merchant_id        = $request->input('merchant_id');
        $payload    = [
            'shop_id'=>$shop_id,
        ];
//        $meituan = self::isvApiList();
//        $meituan->queryShop();
//        if ($shop_id){
//
//        }
    }


    //回调
    public function orderStatusCallback(Request $request){
        $delivery_id    = $request->input('delivery_id');
        $mt_peisong_id  = $request->input('mt_peisong_id');
        $order_id       = $request->input('order_id');
        $status         = $request->input('status');
        $courier_name   = $request->input('courier_name');
        $courier_phone  = $request->input('courier_phone');
        $cancel_rs_id   = $request->input('cancel_reason_id');
        $cancel_reason  = $request->input('cancel_reason');
        $p_deli_time    = $request->input('predict_delivery_time');
        $appkey         = $request->input('appkey');
        $timestamp      = $request->input('timestamp');
        $sign           = $request->input('sign');
        try {
            $data = [
                'delivery_id'   =>$delivery_id,
                'mt_peisong_id' =>$mt_peisong_id,
                'order_id'      =>$order_id,
                'status'        =>$status,
                'courier_name'  =>$courier_name,
                'courier_phone' =>$courier_phone,
                'cancel_reason_id'=>$cancel_rs_id,
                'cancel_reason' =>$cancel_reason,
                'predict_delivery_time'=>$p_deli_time,
                'appkey'        =>$appkey,
                'timestamp'     =>$timestamp,
                'sign'=>$sign,
            ];
            $config = new Config();
            $allow  = $config->verifySign($data);
            if (!$allow){
                \Log::alert(json_encode($data,JSON_UNESCAPED_UNICODE));
                return response()->json(['code'=>1,'msg'=>'签名错误']);
            }
            DB::beginTransaction();
            $record = OrderDelivery::whereDeliveryId($delivery_id)
                ->whereOrderId($order_id)
                ->whereMtPeisongId($mt_peisong_id)
                ->lockForUpdate()
                ->first();
            if (!$record){
                DB::rollBack();
                return response()->json(['code'=>2,'msg'=>'记录不存在']);
            }
            $record->status = $status;
            if ($courier_name)
                $record->courier_name = $courier_name;
            if ($courier_phone)
                $record->courier_phone = $courier_phone;
            if ($cancel_rs_id)
                $record->cancel_reason_id   = $cancel_rs_id;
            if ($cancel_reason)
                $record->cancel_reason      = $cancel_reason;
            if ($p_deli_time)
                $record->predict_delivery_time = $p_deli_time;
            $record->save();
            DB::commit();
        } catch (\Exception $exception){
            DB::rollBack();
            \Log::error('orderStatusCallback:ERROR=>'.$exception->getMessage());
            \Log::error('orderStatusCallback:TRACE=>'.$exception->getTraceAsString());
            return response()->json(['code'=>500]);
        }
        \Log::notice('orderStatusCallback:NOTICE=>$mt_peisong_id=>'.$mt_peisong_id.'--$delivery_id=>'.$delivery_id);
        return response()->json(['code'=>0]);
    }
    public function orderExceptionCallback(Request $request){
        $delivery_id    = $request->input('delivery_id');
        $mt_peisong_id  = $request->input('mt_peisong_id');
        $order_id       = $request->input('order_id');
        $exception_id   = $request->input('exception_id');
        $exception_code = $request->input('exception_code');
        $exception_descr= $request->input('exception_descr');
        $exception_time = $request->input('exception_time');
        $courier_name   = $request->input('courier_name');
        $courier_phone  = $request->input('courier_phone');
        $appkey         = $request->input('appkey');
        $timestamp      = $request->input('timestamp');
        $sign           = $request->input('sign');
    }
    public function deliveryAreaChangeCallback(Request $request){

    }
    public function deliveryRiskChangeCallback(Request $request){

    }
    public function merchantStatusChangeCallback(Request $request){

    }
    public function deliveryPersonDutyChangeCallback(Request $request){

    }
    protected static function isvApiList(): ServiceProviderApiList
    {
        return new ServiceProviderApiList();
    }
    protected function checkCreateShopParameter(Request $request){
        $shop_id        = $request->input('shop_id');
        $shop_name      = $request->input('shop_name');
        $category       = $request->input('category');
        $second_category= $request->input('second_category');
        $contact_name   = $request->input('contact_name');
        $contact_phone  = $request->input('contact_phone');
        $contact_email  = $request->input('contact_email');
        $shop_address   = $request->input('shop_address');
        $shop_address_detail = $request->input('shop_address_detail');
        $shop_lng       = $request->input('shop_lng');
        $shop_lat       = $request->input('shop_lat');
        $coordinate_type    = $request->input('coordinate_type',0);
        $delivery_service_codes = $request->input('delivery_service_codes','4011');
        $business_hours     = $request->input('business_hours');

        if (!$shop_id) return $this->parameterError();
        if (!$shop_name) return $this->parameterError();
        if (!$category) return $this->parameterError();
        if (!$second_category) return $this->parameterError();
        if (!$contact_name) return $this->parameterError();
        if (!$contact_phone) return $this->parameterError();
        if (!$contact_email) return $this->parameterError();
        if (!$shop_address) return $this->parameterError();
        if (!$shop_address_detail) return $this->parameterError();
        if (!$shop_lng) return $this->parameterError();
        if (!$shop_lat) return $this->parameterError();
        if (!$delivery_service_codes) return $this->parameterError();
        if (!$business_hours) return $this->parameterError();
        return false;
    }

}
